<?php

namespace Yolo\Commands;

use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputOption;
use Yolo\Di\DI;
use Yolo\Packages\PackageManager;
use Yolo\Service\ApplicationContainer;

#[Command]
class GetPackageInfo extends HyperfCommand
{
    private ApplicationContainer $applicationContainer;

    private PackageManager $packageManager;

    public function __construct(protected ContainerInterface $container)
    {
        parent::__construct('package:info');

        $this->applicationContainer = DI::use(ApplicationContainer::class);
        $this->packageManager = DI::use(PackageManager::class);
    }

    public function configure(): void
    {
        parent::configure();
        $this->setDescription('Get a package information.');
        $this->addArgument('package', InputOption::VALUE_REQUIRED, 'Package name.');
        $this->addArgument('version', null, 'Package version, default latest version.');
    }

    public function handle(): void
    {
        $package = $this->input->getArgument('package');
        $version = $this->input->getArgument('version') ?? '';

        if ($version) {
            $this->info("Getting package info for $package version: $version");
        } else {
            $this->info("Getting package info for $package latest version");
        }

        $info = $this->packageManager->getPackageInfo($package, $version);

        $this->info("Package details:");
        $this->info("Package name: {$info['name']}");
        $this->info("Package description: {$info['description']}");
        $this->info("Package installed: {$info['installCount']}");
        $this->info("Package version: {$info['version']}");
        $this->info("Package published at: " . date('Y-m-d H:i:s', $info['createdAt']));
        $this->info("Is the latest version: " . ($info['isLatestVersion'] ? 'Yes' : 'No'));

        $installedVersion = $this->packageManager->getDependency($package);
        if ($installedVersion) {

            $this->info("Installed version: $installedVersion");

            if (version_compare($installedVersion, $info['version'], '>')) {
                $this->warn("You are using a newer version of the package.");
            }
        }

        $this->line('');
        $this->line("Install:");
        $this->line("php ./bin/hyperf.php package:install $package $version");
    }
}
